package com.liyuxiang.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liyuxiang.common.rabbit.constant.MqConst;
import com.liyuxiang.common.rabbit.service.RabbitService;
import com.liyuxiang.yygh.common.exception.YyghException;
import com.liyuxiang.yygh.common.helper.HttpRequestHelper;
import com.liyuxiang.yygh.common.result.ResultCodeEnum;
import com.liyuxiang.yygh.enums.OrderStatusEnum;
import com.liyuxiang.yygh.hosp.client.HospitalFeignClient;
import com.liyuxiang.yygh.model.order.OrderInfo;
import com.liyuxiang.yygh.model.user.Patient;
import com.liyuxiang.yygh.order.mapper.OrderMapper;
import com.liyuxiang.yygh.order.service.OrderService;
import com.liyuxiang.yygh.order.service.AlipayService;
import com.liyuxiang.yygh.user.client.PatientFeignClient;
import com.liyuxiang.yygh.vo.hosp.ScheduleOrderVo;
import com.liyuxiang.yygh.vo.msm.MsmVo;
import com.liyuxiang.yygh.vo.order.*;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderInfo> implements OrderService {
    @Autowired
    PatientFeignClient patientFeignClient;
    @Autowired
    HospitalFeignClient hospitalFeignClient;
    @Autowired
    RabbitService rabbitService;
    @Autowired
    AlipayService alipayService;

    public Long saveOrder(String scheduleId, Long patientId) {
        //获取就诊人信息
        Patient patient = patientFeignClient.getPatientOrder(patientId);
        //获取排班相关信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        //判断当前事件是否可预约
        if (new DateTime(scheduleOrderVo.getStartTime()).isAfterNow() || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo, orderInfo);
        String outTeadeNo = System.currentTimeMillis() + "" + new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTeadeNo);
        orderInfo.setScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        baseMapper.insert(orderInfo);

        //调用医院接口，实现预约挂号操作
        //设置调用医院接口需要参数，参数放到map集合
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode", orderInfo.getHoscode());
        paramMap.put("depcode", orderInfo.getDepcode());
        paramMap.put("hosScheduleId", orderInfo.getScheduleId());
        paramMap.put("reserveDate", new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount", orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType", patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex", patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone", patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode", patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode", patient.getDistrictCode());
        paramMap.put("address", patient.getAddress());
        //联系人
        paramMap.put("contactsName", patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo", patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone", patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);

        //请求医院系统接口
//        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        if (result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //发送mq消息，号源更新和短信通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            msmVo.setTemplateCode("TPL_09891");
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                put("patient_name", patient.getName());
                put("hosname", orderInfo.getHosname());
                put("depname", orderInfo.getDepname());
                put("fetch_address", fetchAddress);
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
        return orderInfo.getId();
    }

    @Override
    public boolean cancelOrder(Long orderId) {
        //获取订单信息
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        if (!ObjectUtils.isEmpty(orderInfo)) {
            //判断是否取消
            DateTime quitTime = new DateTime(orderInfo.getQuitTime());
            if (quitTime.isBeforeNow()) {
                throw new YyghException(ResultCodeEnum.CANCEL_ORDER_NO);
            }
            //调用医院接口实现取消预约
            SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
            if (null == signInfoVo) {
                throw new YyghException(ResultCodeEnum.PARAM_ERROR);
            }
            Map<String, Object> reqMap = new HashMap<>();
            reqMap.put("hoscode", orderInfo.getHoscode());
            reqMap.put("hosRecordId", orderInfo.getHosRecordId());
            reqMap.put("timestamp", HttpRequestHelper.getTimestamp());
            String sign = HttpRequestHelper.getSign(reqMap, signInfoVo.getSignKey());
            reqMap.put("sign", sign);
            System.err.println(signInfoVo.getApiUrl() + "/order/updateCancelStatus");
            JSONObject result = HttpRequestHelper.sendRequest(reqMap,
                    "http://localhost:9998/order/updateCancelStatus");
            //根据医院接口返回数据
            if (result.getInteger("code") != 200) {
                throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
            } else {
                //如果该订单是没有支付状态，那么直接更新订单的信息，不需要走退款流程
                if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.UNPAID.getStatus().intValue()) {
                    return this.updateOrderInfo(orderInfo);
                }
                //判断当前订单是否可以取消  可以的话调用微信退款方法
                if (orderInfo.getOrderStatus().intValue() == OrderStatusEnum.PAID.getStatus().intValue()) {
                    //退款
                    Boolean isRefund = alipayService.refund(orderId);
                    if (!isRefund) {
                        throw new YyghException(ResultCodeEnum.CANCEL_ORDER_FAIL);
                    }
                    return this.updateOrderInfo(orderInfo);
                }
            }
        }
        return false;
    }

    @Override
    public Page<OrderInfo> getOrderPageByUserId(Page<OrderInfo> page, OrderQueryVo orderQueryVo, Long userId) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(orderQueryVo.getPatientId() != null, OrderInfo::getPatientId, orderQueryVo.getPatientId());
        queryWrapper.eq(OrderInfo::getUserId, userId);
        queryWrapper.eq(orderQueryVo.getOrderStatus() != null, OrderInfo::getOrderStatus, orderQueryVo.getOrderStatus());
        Page<OrderInfo> orderInfoPage = baseMapper.selectPage(page, queryWrapper);
        orderInfoPage.getRecords().stream().forEach(i -> {
            this.packageOrderInfo(i);
        });
        return orderInfoPage;
    }

    @Override
    public OrderInfo getOrderById(Long id) {
        return this.packageOrderInfo(baseMapper.selectById(id));
    }

    @Override
    public void patientTips() {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getReserveDate, new DateTime().toString("yyyy-MM-dd"));
        queryWrapper.ne(OrderInfo::getOrderStatus, OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        orderInfoList.stream().forEach(i -> {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(i.getPatientPhone());
            msmVo.setTemplateCode("TPL_09897");
            String reserveDate = new DateTime(i.getReserveDate()).toString("yyyy-MM-dd") + (i.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", i.getHosname() + "|" + i.getDepname() + "|" + i.getTitle());
                put("reserveDate", reserveDate);
                put("patient_name", i.getPatientName());
            }};
            msmVo.setParam(param);
            //短信提醒是借助前面我们写的短信mq，这里是短信生产者
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        });
    }

    @Override
    public Map<String, Object> getCountMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountVoList = baseMapper.selectOrderCount(orderCountQueryVo);
        List<String> dateList = orderCountVoList.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        List<Integer> countList = orderCountVoList.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }

    private OrderInfo packageOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }

    private boolean updateOrderInfo(OrderInfo orderInfo) {
        try {
            //更新订单状态
            orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
            baseMapper.updateById(orderInfo);

            //发送mq更新预约数量
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(orderInfo.getScheduleId());
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime() == 0 ? "上午" : "下午");
            Map<String, Object> param = new HashMap<String, Object>() {{
                put("title", orderInfo.getHosname() + "|" + orderInfo.getDepname() + "|" + orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }
}
